import { createStore, createLogger } from "vuex";
import axios from "axios";
import router, { staticRoutes } from "@/router";
interface UserInfoState {
  token: string;
  nickname: string;
  role: string;
  avator: string;
  isLogin: boolean;
}

export interface RootState {
  userInfo: UserInfoState;
}

const store = createStore<RootState>({
  state: {
    userInfo: {
      // 用户令牌
      token: "",
      nickname: "",
      role: "",
      avator: "",
      isLogin: false,
    },
  },
  mutations: {
    loginSuccess(state, payload: UserInfoState) {
      // 保存用户信息
      state.userInfo = payload;

      // 获取角色
      const role = state.userInfo.role;
      // 动态生成路由
      const danamicRoutes = staticRoutes
        .filter((route) => {
          // 路由没有要求权限
          if (!route.meta) return true;
          // 当前用户是 管理员
          if (role === "admin") return true;
          // 权限验证
          return route.meta.role === role;
        })
        .forEach((route) => {
          // 添加动态路由
          router.addRoute("mainLayout", route);
        });
    },
    loginFail(state) {
      state.userInfo = {
        token: "",
        nickname: "",
        role: "",
        avator: "",
        isLogin: false,
      };
    },
  },
  actions: {
    async login(context, data: { username: string; password: string }) {
      try {
        const resp = await axios.post("/api/login", data);
        context.commit("loginSuccess", { ...resp.data.data, isLogin: true });
        return resp;
      } catch {
        context.commit("loginFail");
        return Promise.reject("登录失败，请重新登录");
      }
    },
    async quit(context) {
      context.commit("loginFail");
      staticRoutes.forEach((route) => {
        if (route.name) router.removeRoute(route.name);
      });
    },
  },
  plugins: [createLogger()],
});

// 订阅仓库
store.subscribe((m, state) => {
  localStorage.setItem("token", state.userInfo.token);
});

export default store;
